package com.duke.shaking.profile;

import java.io.InputStream;
import java.net.URL;
import java.util.List;

import com.androidquery.AQuery;
import com.duke.shaking.R;
import com.duke.shaking.pojo.UserImage;
import com.duke.shaking.profile.URL2DrawableTask.OnCompletionListener;
import com.duke.shaking.widget.GalleryAdapter;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.FrameLayout.LayoutParams;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;

public class ViewPhotosImageSwitcherActivity extends Activity implements
		ViewFactory, OnItemSelectedListener {
	public static final String TAG = "ViewPhotosImageSwitcherActivity";
	public static final String EXTRA_IMAGES = "images";
	
	private ImageSwitcher is;  
    private Gallery g;  
    
    private List<UserImage> imageList;
    private AQuery aQuery;
      
    //选中的索引  
    private int selected = 0;  
    //手势向上向下 落点 x 坐标  
    private int upX,downX;
    
	public ViewPhotosImageSwitcherActivity() {
		super();
		this.aQuery = new AQuery(this);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		Intent i = getIntent();
		imageList = (List<UserImage>)i.getSerializableExtra(EXTRA_IMAGES);
		
		//全屏设置  
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
          
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);  
        setContentView(R.layout.activity_gallery3);  
          
        //得到ImageSwitcher对象  
        is = (ImageSwitcher) findViewById(R.id.imageSwitcher1);  
        //实现并设置工厂内部接口的makeView方法，用来显示视图。  
        is.setFactory(ViewPhotosImageSwitcherActivity.this);  
          
        is.setOnTouchListener(touchListener);  
        //设置图片来源  
        g = (Gallery) findViewById(R.id.gallery);  
        g.setAdapter(new GalleryAdapter(this, imageList));  
        g.setOnItemSelectedListener(this);  
          
        //设置切入动画  
        is.setInAnimation(AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_in));  
        //设置切出动画  
        is.setAnimation(AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_out));  
	}
	
	OnTouchListener touchListener = new OnTouchListener() {  
        
        public boolean onTouch(View v, MotionEvent event) {  
              
            if(event.getAction()==MotionEvent.ACTION_DOWN) {  
                //取得 按下时的 x坐标  
                downX = (int) event.getX();  
                //True if the listener has consumed the event, false otherwise.  
                //我的理解是：如果event销毁了，结束了一个时间，就返回true；下一个event is new  
                return true;  
            } else if(event.getAction()==MotionEvent.ACTION_UP) {  
                //取得 松开时的 x坐标  
                upX = (int)event.getX();  
                //手指 向右划， 看前一张  
                if(upX-downX>100) {  
                    //如果是第一张，则给出 最后一张照片（前一张）  
                    if(g.getSelectedItemPosition()==0) {  
                        selected = g.getCount()-1;  
                    } else {  
                        selected = g.getSelectedItemPosition() - 1; // 上一张  
                    }  
                } else if(downX - upX>100) {  
                    //手指 向左划， 看下一张  
                      
                    if(g.getSelectedItemPosition()==g.getCount()-1) {  
                        selected = 0;  
                    } else {  
                        selected = g.getSelectedItemPosition() + 1;// 下一张  
                    }  
                }  
                  
                //int position, boolean animate  
                g.setSelection(selected,true);  
                return true;  
            }  
            return false;  
        }  
    };
    private int pos;
    public void onItemSelected(AdapterView<?> arg0, View arg1, int position,  
            long arg3) {  
    	Log.i(TAG, "onItemSelected");
    	
    	String url = imageList.get(position).getUrl();
        pos = position;
        
        URL2DrawableTask task = new URL2DrawableTask();
        task.setOnCompletionListener(new OnCompletionListener() {
			
			public void onTaskComplete(Drawable result) {
				is.setImageDrawable(result);
				selected = pos;
			}
		});
        task.execute(url);
    } 
	
    
    public Drawable LoadImageFromWebOperations(String url) {
        try {
            InputStream is = (InputStream)new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        } catch (Exception e) {
            System.out.println("Exc=" + e);
            return null;
        }
    }
  
    public void onNothingSelected(AdapterView<?> arg0) {  
          
    }  
  
    public View makeView() {  
        ImageView i = new ImageView(this);  
        i.setBackgroundColor(0xFF000000);  
        i.setScaleType(ImageView.ScaleType.FIT_CENTER);  
        i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));  
        return i;  
    }  

}
